#include <stdio.h>
#include <stdlib.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define TSOCKET int

TSOCKET openSocket(int port, char *ip)
{
  TSOCKET sock = socket( AF_INET, SOCK_STREAM, 0 );
//  printf("Created Socket!\n");

  struct sockaddr_in sain;
  sain.sin_family = AF_INET;
  sain.sin_port = htons(port);
  sain.sin_addr.s_addr = inet_addr(ip);

  if(connect( sock,(struct sockaddr *)&sain, sizeof(sain) )==-1) {
//    printf("connection error\n");
    return 0;
  } else {
//    printf("connected!!\n");
  }

  return sock;
}


TSOCKET openServerSocket(int port)
{
  TSOCKET sock = socket( AF_INET, SOCK_STREAM, 0 );
//  printf("Created Socket!\n");

  struct sockaddr_in sain;
  sain.sin_family = AF_INET;
  sain.sin_addr.s_addr = INADDR_ANY;
  sain.sin_port = htons(port);

  if (bind(sock, (struct sockaddr *) &sain,
              sizeof(sain)) < 0) 
              error("ERROR on binding");
  listen(sock,5);

  return sock;
}

TSOCKET acceptClient(TSOCKET serverSocket)
{
  struct sockaddr_in cli_addr;
  socklen_t clilen;

  clilen = sizeof(cli_addr);
  TSOCKET newsockfd = accept(serverSocket, 
              (struct sockaddr *) &cli_addr, 
              &clilen);

  return newsockfd;
}

void redirect(TSOCKET server1)
{
  TSOCKET socket1 = openSocket(8000,"192.168.25.9");
  TSOCKET socket2 = openSocket(8000,"192.168.25.9");
//  TSOCKET socket1 = openSocket(80,"173.194.118.17");

  char buffer[4096];
  while(1) {
    int rdLen = recv(server1, buffer, 4096, MSG_DONTWAIT);
    if(rdLen>=0){
      write(socket1, buffer, rdLen);
      write(socket2, buffer, rdLen);
    }

    rdLen = recv(socket1, buffer, 4096, MSG_DONTWAIT);
    if(rdLen>=0){
      write(server1, buffer, rdLen);
    }
  }  
}

int main(int argc, char *argv[], char *env[])
{
  TSOCKET server = openServerSocket(8001);
  printf("server open!\n");

  while(1) {
    TSOCKET server1 = acceptClient(server);
    printf("accepted!\n");
    if(!fork()) {
      redirect(server1);
    }
  }

  return 0;
}
